/*
 * TreeProApp.java
 */

package treepro;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.jdesktop.application.Action;
import org.jdesktop.application.Application;
import org.jdesktop.application.SingleFrameApplication;

/**
 * The main class of the application.
 */
public class TreeProApp extends SingleFrameApplication {
    
    public static TreeProView main;
    public static TableDialog tableDialog = null;
    public static RunDialog runDialog = null;
    public static RandomDialog randomDialog = null;
    public static boolean inProcess = false;
    public static Date dateStart = null;
    public static calcsdk.Calcsdk calcsdk = null;
    public static List<int[]> paths = new ArrayList<int[]>();    
    public static ResultFrame resultFrame = null;
    public static File fileName = new File("Новый.xml");
    public static ArrayList<int[]> resultPaths = new ArrayList<int[]>();
    public static ArrayList<BeanLoop> loopPaths = new ArrayList<BeanLoop>();
    public static int startNode;
    public static Double avtoMassa;
    public static Double avtoFreeMassa;
    

    /**
     * At startup create and show the main frame of the application.
     */
    @Override protected void startup() {
        show(new TreeProView(this));
        jfc = new JFileChooser();
        jfc.setAcceptAllFileFilterUsed(false);
        jfc.addChoosableFileFilter(new FileNameExtensionFilter("xml", "xml"));        
        
    }

    /**
     * This method is to initialize the specified window by injecting resources.
     * Windows shown in our application come fully initialized from the GUI
     * builder, so this additional configuration is not needed.
     */
    @Override protected void configureWindow(java.awt.Window root) {
    }

    /**
     * A convenient static getter for the application instance.
     * @return the instance of TreeProApp
     */
    public static TreeProApp getApplication() {
        return Application.getInstance(TreeProApp.class);
    }

    /**
     * Main method launching the application.
     */
    public static void main(String[] args) {
        launch(TreeProApp.class, args);
    }

    public static String titleDivasoft = "Divasoft TreePro - ";
    
    @Action
    public void file_new() {
        if (JOptionPane.showConfirmDialog(main.getFrame(), 
                "Текущий граф не будет сохранен, продолжить?", "Новый граф", 
                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)==JOptionPane.YES_OPTION) {

            main.clearResults();
            main.treePanel.objects.clear();
            main.treePanel.updateTable();
            TreeProApp.resultPaths.clear();
            TreeProApp.loopPaths.clear();
            TreeProApp.paths.clear();
            
            main.treePanel.repaint();
            
            if (tableDialog==null)
                tableDialog = new TableDialog(main.getFrame(), true);
            set_size();
            if (JOptionPane.showConfirmDialog(main.getFrame(), 
                "Заполнить граф автоматически?", "Генератор случайных данных", 
                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)==JOptionPane.YES_OPTION)
                tableDialog.setVisible(true);
            else
                
            main.getFrame().setTitle(titleDivasoft+"Новый.xml");
            fileName = new File("Новый.xml");
        }
        
    }
    
    JFileChooser jfc = null;
    
    @Action
    public void file_open() {
        
        if (jfc.showOpenDialog(main.getFrame())==JFileChooser.APPROVE_OPTION) {
            main.treePanel.loadFromFile(jfc.getSelectedFile());
        }
    }

    @Action
    public void file_save() {
        if (jfc.showSaveDialog(main.getFrame())==JFileChooser.APPROVE_OPTION) {
            String fName = jfc.getSelectedFile().toString();
            FileFilter filter = jfc.getFileFilter();
            if (!fName.endsWith("."+filter.getDescription()))
                fName+="."+filter.getDescription();
            File file = new File(fName);
            if (file.exists())
                if (JOptionPane.showConfirmDialog(main.getFrame(), "Файл с таким именем уже существует, перезаписать?", 
                        "Подтвердите", JOptionPane.YES_NO_OPTION, 
                        JOptionPane.QUESTION_MESSAGE)!=JOptionPane.YES_OPTION)
                    return;
            main.treePanel.saveToFile(file);
        }        
    }

    @Action
    public void save_image() {
        try {
            JFileChooser jfcLocal = new JFileChooser();
            jfcLocal.setAcceptAllFileFilterUsed(false);
            
            jfcLocal.addChoosableFileFilter(new FileNameExtensionFilter("jpg", "jpg"));
            jfcLocal.addChoosableFileFilter(new FileNameExtensionFilter("gif", "gif"));
            jfcLocal.addChoosableFileFilter(new FileNameExtensionFilter("png", "png"));

            if (jfcLocal.showSaveDialog(main.getFrame())==JFileChooser.APPROVE_OPTION) {
                String fileNameLocal = jfcLocal.getSelectedFile().toString();
                FileFilter filter = jfcLocal.getFileFilter();
                if (!fileNameLocal.endsWith("."+filter.getDescription()))
                    fileNameLocal+="."+filter.getDescription();
                File file = new File(fileNameLocal);
                if (file.exists())
                    if (JOptionPane.showConfirmDialog(main.getFrame(), "Файл с таким именем уже существует, перезаписать?", 
                            "Подтвердите", JOptionPane.YES_NO_OPTION, 
                            JOptionPane.QUESTION_MESSAGE)!=JOptionPane.YES_OPTION)
                        return;
                ImageIO.write(main.treePanel.buffer, filter.getDescription(), file);
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(main.getFrame(), "Не могу сохранить изображение, ошибка: "+
                    e.getLocalizedMessage(), "Ошибка", JOptionPane.ERROR_MESSAGE);
        }        
    }

    @Action
    public void set_size() {
        main.treePanel.setScreenSize(new SetSizeDialog(main.getFrame(), true).execute(main.treePanel.getScreenWidth(), main.treePanel.getScreenHeight()));
    }

    @Action
    public void new_node() {
        main.addLinkBtn.setSelected(false);
        if (!main.addNodeBtn.isSelected())
            main.treePanel.command = 0;
        else {
            main.addLinkBtn.setSelected(false);
            main.treePanel.command = 1;
        }
        
    }

    @Action
    public void add_link() {
        main.addNodeBtn.setSelected(false);
        if (main.addLinkBtn.isSelected())
            main.treePanel.command = 2;
        else {
            //main.addLinkBtn.setSelected(false);
            main.treePanel.command = 0;
        }
       
    }

    @Action
    public void delete_object() {
        if (JOptionPane.showConfirmDialog(main.getFrame(), "Удалить объект?", "Подтвердите", 
                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)==JOptionPane.YES_OPTION) {
            main.treePanel.deleteSelected();
            main.actionMap.get("delete_object").setEnabled(false);
            main.actionMap.get("object_properties").setEnabled(false);            
        }
            
        
        
    }
/*
    @Action
    public void zoom_in() {
    }

    @Action
    public void zoom_out() {
    }
*/
    @Action
    public void move_up() {
        main.treePanel.move_up();
    }

    @Action
    public void move_down() {
        main.treePanel.move_down();
    }

    @Action
    public void move_left() {
        main.treePanel.move_left();
    }

    @Action
    public void move_right() {
        main.treePanel.move_right();
    }

    @Action
    public void delete_links() {
        if (JOptionPane.showConfirmDialog(main.getFrame(), "Удалить все связи?", "Подтвердите", 
                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)==JOptionPane.YES_OPTION)
            main.treePanel.removeLinks();
    }

    @Action
    public void link_orient() {
        main.treePanel.addOrient();
    }

    @Action
    public void link_select() {
        main.treePanel.link_select();
    }

    @Action
    public void object_properties() {
        main.treePanel.setProperties();
    }

    
    
    @Action
    public void create_table() {
        if (randomDialog==null)
            randomDialog = new RandomDialog(main.getFrame(), true);
        if (main.treePanel.getLines().size()<2) {
            JOptionPane.showMessageDialog(main.getFrame(), "Недостаточно данных для выполнения операции. Добавьте вершины и установите связи.", 
                    "Отменено", JOptionPane.WARNING_MESSAGE);
            return;
        }
        randomDialog.setVisible(true);
    }

    @Action
    public void resize_table() {
        main.treePanel.createNode(new Random().nextInt(main.treePanel.getScreenWidth()), new Random().nextInt(main.treePanel.getScreenHeight()));
    }

    @Action
    public void view_result() {
        TreeProApp.resultFrame.setVisible(!TreeProApp.resultFrame.isVisible());
    }
}
